package com.wwzh.interview.study.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyResource{
    private volatile boolean flag = true ;// 默认开启，进行生产+消费
    private AtomicInteger atomicInteger = new AtomicInteger();
    BlockingQueue<String> blockingQueue = null;

    public MyResource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println(blockingQueue.getClass().getName());
    }
    public void myProd() throws Exception{
        String data = null;
        boolean value ;
        while (flag){
            data = atomicInteger.incrementAndGet() + "";
            value = blockingQueue.offer(data,2L, TimeUnit.SECONDS);
            if(value){
                System.out.println(Thread.currentThread().getName() + "\t 插入队列成功");
            }else {
                System.out.println(Thread.currentThread().getName() + "\t 插入队列失败");
            }
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(Thread.currentThread().getName()+"\t 大老板叫停了，表示falg=false 生产结束");
    }

    public void myConsumer() throws Exception{
        String result = null;
        while (flag){
            result = blockingQueue.poll(2L, TimeUnit.SECONDS);
            if(null == result || result.equalsIgnoreCase("")){
                flag = false;
                System.out.println(Thread.currentThread().getName() + "\t 超过2s没有");
                System.out.println();
                return;
            }else {
                System.out.println(Thread.currentThread().getName() + "\t 消费队列成功");
            }
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(Thread.currentThread().getName()+"\t 大老板叫停了，表示falg=false 生产结束");
    }

    public void stop() {
        flag = false;
    }
}
public class ProdConsumer_BlockQueueDemo {
    public static void main(String[] args) {
        MyResource myResource = new MyResource(new LinkedBlockingQueue<>(10));
        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName()+"\t 生产");
                myResource.myProd();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"AA").start();
        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName()+"\t 消费");
                myResource.myConsumer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"BB").start();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println();
        myResource.stop();

    }
}
